package mvc.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XMLUtil {

public static Map<String,XmlBean> getActionInfo(String xmlPath){
	SAXReader reader = new SAXReader();
	Map<String,XmlBean> actionMap = new HashMap<String, XmlBean>();
	try {
		Document doucument = reader.read(new File(xmlPath));
		Element element = doucument.getRootElement();
		Element amap = element.element("actionmap");
		List actions = amap.elements("action");
		for(Iterator it = actions.iterator();it.hasNext();){
			Element ac = (Element)it.next();
			String path = ac.attributeValue("path");
			String className = ac.attributeValue("type");
			String name = ac.attributeValue("name");
			Map<String,String> pages = new HashMap<String, String>();
			List<Element> pagesInfo = ac.elements();
			for(Element e : pagesInfo){
				String na = e.attributeValue("name");
				String pa = e.attributeValue("path");
				pages.put(na, pa);
			}
			String formtype = "";
			List forms = element.element("formbean").elements("form");
			for(Iterator ite = forms.iterator();ite.hasNext();){
				Element ele = (Element)ite.next();
				String fname = ele.attributeValue("name");
				if(fname.equals(name)){
					formtype = ele.attributeValue("type");
					break;
				}
			}
			XmlBean xBean = new XmlBean();
			xBean.setActionName(className);
			xBean.setFormName(formtype);
			xBean.setPath(path);
			xBean.setPages(pages);
			actionMap.put(path, xBean);
			
		}
	} catch (DocumentException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		System.out.println("mvc.xml加载失败！");
	}	
//	Document doc = 
	return actionMap;
}
public static void main(String[] args) {
	Map<String,XmlBean> beans = XMLUtil.getActionInfo("E:\\workspace\\mvc_t\\WebContent\\WEB-INF\\mvc.xml");
	for(Iterator<String> ite = beans.keySet().iterator();ite.hasNext();){
		String key = ite.next();
		XmlBean xb = beans.get(key);
		
		System.out.println(key + "---" + xb.getActionName() + "---" + xb.getFormName() + "-----" + xb.getPath() );
	}
	System.out.println(beans);
}
}
